package com.fengzhi.crawler.jsoup.Fetcher.impl;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import com.fengzhi.crawler.jsoup.Fetcher.ImgFetcher;

public class ImgFetcherImpl implements ImgFetcher {

	/**
	 * 
	 * @Description: TODO(提取页面中的图像)
	 * @param imgUrl
	 *            图像地址
	 * @param filePath
	 *            保存地址
	 * @return 图像文件保存地址
	 */
	public String fetch(String imgUrl, String dirPath) {
		// 创建目录
		this.createDir(dirPath);

		// 文件存储绝对路径
		String fileName = imgUrl.substring(imgUrl.lastIndexOf("/") + 1);
		String imgPath = dirPath + fileName;

		// 输出流、输入流、url连接、url
		FileOutputStream fos = null;
		BufferedInputStream bis = null;
		HttpURLConnection httpUrl = null;
		URL url = null;

		// 一次读取数据大小
		int BUFFER_SIZE = 1024;
		byte[] buf = new byte[BUFFER_SIZE];
		int size = 0;

		try {
			// 连接
			url = new URL(imgUrl);
			httpUrl = (HttpURLConnection) url.openConnection();
			httpUrl.connect();

			// 获取输入流
			bis = new BufferedInputStream(httpUrl.getInputStream());
			// 创建输出流
			fos = new FileOutputStream(imgPath);

			// 读取数据
			while ((size = bis.read(buf)) != -1) {
				fos.write(buf, 0, size);
			}

			fos.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassCastException e) {
			e.printStackTrace();
		} finally {
			try {
				fos.close();
				bis.close();
				httpUrl.disconnect();
			} catch (IOException e) {

			} catch (NullPointerException e) {
			}
		}

		return imgPath;
	}

	/**
	 * 
	 * @Title: createDir
	 * @Description: TODO(创建目录)
	 * @author fyf
	 * @param dir
	 */
	public void createDir(String dir) {
		File file = new File(dir);

		if (!file.exists()) {
			file.mkdirs();
		}
	}
}
